package com.example.exam.config;

import com.example.exam.realm.UserRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shishuqian
 * date 2021/5/12
 * time 15:56
 **/
//@Configuration
public class ShiroConfig {

    /**
     * 将accountRealm 注入到ioc容器中
     * bean的名字是方法名
     */
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    /**
     * 根据 bean的名字，从ioc中取出accountRealm
     * 将accountRealm注入到 DefaultWebSecurityManager中
     */
    @Bean
    public DefaultWebSecurityManager securityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    /**
     * 将securityManager注入到 shiroFilterFactoryBean 中
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);
        //权限设置
        Map<String,String> filterChainDefinitionMap = new HashMap<>();
        //所有的页面都需要登录
        filterChainDefinitionMap.put("/**","authc");
        //filterChainDefinitionMap.put("/login","login");
        filterChainDefinitionMap.put("/logout","logout");
        factoryBean.setLoginUrl("/login");
        factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return factoryBean;
    }

    //@Bean
    public SimpleCookie rememberMeCookie(){
        //这个参数是cookie的名称，对应前端的checkbox的name = rememberMe
        SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
        //setcookie的httponly属性如果设为true的话，会增加对xss防护的安全系数。它有以下特点：
        //setcookie()的第七个参数
        //设为true后，只能通过http访问，javascript无法访问
        //防止xss读取cookie
        simpleCookie.setHttpOnly(true);
        simpleCookie.setPath("/");
        //记住我cookie生效时间 ,单位秒
        simpleCookie.setMaxAge(30);
        return simpleCookie;
    }
}
